<?php
/**
 * admin service file Created by PhpStorm.
 * User: wumengmeng
 * Date: 2019/12/05
 * Time: 14:09
 */

namespace Modules\Shop\Service;

use HiCommon\Repository\MaintainShopRepository;
use HiCommon\Repository\MaintainConfigRepository;
use HiCommon\Repository\GoodsRepository;
use HiCommon\Repository\MaintainShopGoodsRepository;
use HiCommon\Repository\VehicleModelRepository;
use HiCommon\Repository\MaintainVehicleModelRepository;

class MaintainShopService
{
    /**
     * 获取所有权限
     * @return array
     */
    public function get_all()
    {
        try {
            $arr_option = ['order' => ['key' => 'id', 'value' => 'asc']];
            $data = MaintainShopRepository::get_all($arr_option)->toarray();
            return hello_success('成功', $data);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 获取分页数据
     * @param $arr_input
     * @return array
     */
    public function get_list($arr_input)
    {
        try {
            $arr_option = [
                'where' => ['shop_id' => $arr_input['shop_id']],
                'with' => ['father_config', 'son_config',/* 'maintain_shop_goods'*/],
            ];
            $data = MaintainShopRepository::get_list($arr_option);
            $data = list_page_data($data);

            $list['page'] = $data['page_data'];
            $item = [];
            foreach ($data['data'] as $key => $value) {
                $item[$value['maintain_config_pid']]['f_id'] = $value['maintain_config_pid'];
                $item[$value['maintain_config_pid']]['f_name'] = $value['father_config']['name'];
                $item[$value['maintain_config_pid']]['son'][] = [
                    'maintain_shop_id' => $value['id'],
                    'name' => $value['son_config']['name'],
                    'custom_title' => $value['custom_title'],
                ];
            }
            $list['data'] = $item;

            return hello_success('成功', $list);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 添加一条数据
     * @param $arr_input
     * @return array
     */
    public function add_one($arr_input)
    {
        $arr_input = hi_array_del_null($arr_input);
        try {
            $goods_array = $arr_input['goods'];
            unset($arr_input['goods']);

            //添加
            $res = MaintainShopRepository::add_one($arr_input)->toarray();
            $goods_info = [];
            $time = date('Y-m-d H:i:s');
            foreach ($goods_array as $key => $value) {
                if (!empty($value['product_id'])) {
                    $goods_info[] = [
                        'maintain_shop_id' => $res['id'],
                        'goods_id' => $value['goods_id'],
                        'product_id' => $value['product_id'],
                        'num' => intval($value['num']),
                        'created_at' => $time,
                        'updated_at' => $time
                    ];
                }
            }

            if (empty($goods_info)) {
                return hello_error('请配置商品');
            }

            $result = MaintainShopGoodsRepository::add_many($goods_info);

            if (empty($res) || empty($result)) {
                return hello_error('添加失败');
            }

            return hello_success('成功', $res);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 查询一条数据
     * @param int $n_id
     * @return array
     */
    public function get_one(int $n_id)
    {
        try {
            $n_id = (int)$n_id;
            if ($n_id <= 0) {
                hello_error('数据ID不能为空');
            }

            //查询
            $arr_option['with'] = ['maintain_shop_goods_one'];
            $res = MaintainShopRepository::get_one($n_id, $arr_option)->toarray();

            $data['maintain_shop_id'] = $res['id'];
            $data['maintain_config_id'] = $res['maintain_config_id'];
            $data['custom_title'] = $res['custom_title'];
            foreach ($res['maintain_shop_goods_one'] as $key => $value) {
                $data['product'][] = $value['product_id'];
                $data['maintain_shop_goods'][$value['goods_id']] = $value['num'];
            }

            if (empty($data)) {
                return hello_error('查询失败');
            }

            return hello_success('查询成功', $data);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 修改一条数据
     * @param array $arr_input
     * @return array
     */
    public function edit_one(array $arr_input)
    {
        $arr_input = hi_array_del_null($arr_input);
        try {
            $del_where['maintain_shop_id'] = $arr_input['maintain_shop_id'];
            MaintainShopGoodsRepository::delete_by_where($del_where, true);

            $time = date('Y-m-d H:i:s');
            $goods_info = [];
            foreach ($arr_input['goods'] as $key => $value) {
                if (!empty($value['product_id'])) {
                    $goods_info[] = [
                        'maintain_shop_id' => $arr_input['maintain_shop_id'],
                        'goods_id' => $value['goods_id'],
                        'product_id' => $value['product_id'],
                        'num' => $value['num'],
                        'created_at' => $time,
                        'updated_at' => $time
                    ];
                }
            }

            $res = MaintainShopGoodsRepository::add_many($goods_info);

            $up_input = [
                'id' => $arr_input['maintain_shop_id'],
                'custom_title' => $arr_input['custom_title']
            ];
            $result = MaintainShopRepository::edit_one($up_input);

            if ($res && $result) {
                return hello_success('修改成功！');
            }

            return hello_error('修改失败！');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 修改单个字段
     * @param $arr_input
     * @return array
     */
    public function change_one_state($arr_input)
    {
        try {
            $arr_input['id'] = (int)$arr_input['id'];
            if ($arr_input['id'] <= 0) {
                return hello_error('数据id不能为空');
            }

            $res = MaintainShopRepository::edit_one($arr_input);
            if ($res === false) {
                return hello_error('操作失败');
            }
            return hello_success('成功');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 删除一条数据
     * @param $type
     * @param $n_id
     * @return array
     */
    public function delete_one($type, $n_id)
    {
        try {
            if ($n_id <= 0) {
                return hello_error('数据id不能为空');
            }

            if ($type == 1) {
                $arr_option['where'] = ['maintain_config_pid' => $n_id];
                $arr_option['field'] = ['id'];
                $data = MaintainShopRepository::get_all($arr_option)->toarray();
                $array_id = array_column($data, 'id');
                MaintainShopGoodsRepository::delete_by_where_in($array_id);

                $del_where['maintain_config_pid'] = $n_id;
                $res = MaintainShopRepository::delete_by_where($del_where);
            } else {
                $del_where['maintain_shop_id'] = $n_id;
                MaintainShopGoodsRepository::delete_by_where($del_where);
                $res = MaintainShopRepository::delete_one($n_id);

                $array_id = [$n_id];
            }

            MaintainVehicleModelRepository::delete_by_where_in($array_id);

            if ($res === false) {
                return hello_error('操作失败');
            }
            return hello_success('成功');

        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 获取保养配置
     * @param int $pid
     * @return array
     */
    public function get_maintain_config($pid = 0)
    {
        try {
            $shop_id = shop_shop_id();
            $arr_Shop['where'] = ['shop_id' => $shop_id];
            $arr_Shop['field'] = ['id', 'maintain_config_id'];

            //$info = MaintainShopRepository::get_all($arr_Shop)->toarray();
            // $have = array_column($info, 'maintain_config_id');//门店已有的配置id数组

            $arr_option = ['field' => ['id', 'pid', 'name'], 'where' => ['pid' => $pid]];
            $data = MaintainConfigRepository::get_all($arr_option)->toarray();

            $result = [];
            foreach ($data as $key => $value) {
                //if (!in_array($value['id'], $have)) {
                $result[] = $value;
                // }
            }

            return hello_success('成功', $result);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 获取该门店的商品列表
     * @param $arr_input
     * @return array
     */
    public function get_goods_list($arr_input)
    {
        try {
            $arr_option = [
                'field' => ['id', 'name', 'title', 'pic_url', 'maintain_pid', 'maintain_id'],
                'where' => ['repairstore_id' => $arr_input['shop_id'], 'status' => 1],
                'with' => ['product']
            ];

            if (!empty($arr_input['maintain_config_id'])) {
                $arr_option['where']['maintain_id'] = $arr_input['maintain_config_id'];
            }

            $data = GoodsRepository::get_all_to_shop($arr_option)->toArray();

            return hello_success('成功', $data);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 获取汽车品牌列表和该该保养适用的车型列表
     * @param int $n_id
     * @return array
     */
    public function maintain_vehicle(int $n_id)
    {
        try {
            if ($n_id <= 0) {
                hello_error('数据ID不能为空');
            }
            $result = self::get_vehicle_child();//车型

            //获取已经配置的车型
            $arr_option = [
                'where' => ['maintain_shop_id' => $n_id],
                'with' => ['vehicle_model'],
                'field' => ['id', 'maintain_shop_id', 'vehicle_model_id'],
            ];
            $data = MaintainVehicleModelRepository::get_all($arr_option)->toarray();

            $oldList = [];
            foreach (array_column($data, 'vehicle_model') as $key => $value) {
                $pid = $value['parent']['parentid'];
                $oldList[$pid]['parent_id'] = $pid;
                $oldList[$pid]['parent_name'] = $value['parent']['name'];
                $oldList[$pid]['name'][] = [
                    'id' => $value['id'],
                    'name' => $value['name'],
                ];
                if ($key == 0) {
                    $result['parent_id'] = $pid;
                }
            }
            $result['vehicle_model_ids'] = array_column($data, 'vehicle_model_id');//第二级选中的值
            $result['vehicle_model_data'] = $oldList;

            return hello_success('查询成功', $result);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 获取指定品牌下的汽车分类
     * @param int $n_pid
     * @return array
     */
    public function get_vehicle_child($n_pid = 0)
    {
        $vehicle = self::vehicle_model_top_list($n_pid);

        $result = [];
        foreach ($vehicle['data'] as $key => $value) {
            $list = [];
            foreach ($value['children'] as $it => $item) {
                $list[$it]['id'] = $item['id'];
                $list[$it]['pid'] = $n_pid;
                $list[$it]['title'] = $item['name'];
            }
            $result['vehicle'][$key]['id'] = $value['id'];
            $result['vehicle'][$key]['pid'] = $n_pid;
            $result['vehicle'][$key]['title'] = $value['title'];
            $result['vehicle'][$key]['children'] = $list;
            $result['vehicle'][$key]['spread'] = true;
            if ($n_pid == 0) {
                $result['cell'][] = $value['title'];
            }
        }

        return $result;
    }

    /**
     * 车型列表
     * @param int $n_pid
     * @return array
     */
    public function vehicle_model_top_list($n_pid = 0)
    {
        $n_pid = intval($n_pid);
        if ($n_pid == 0) {
            $arr_option = [
                'where' => ['parentid' => $n_pid],
                'field' => ['id', 'name', 'fullname', 'initial', 'parentid', 'logo', 'depth'],
            ];
            $res = VehicleModelRepository::base_get_all($arr_option)->toarray();
            $res = collect($res)->sortBy('id')->sortBy('initial')->groupBy('initial')->map(function ($value, $key) {
                $value = [
                    'title' => $key,
                    'children' => $value->toArray(),
                ];
                return $value;
            })->values()->toArray();

        } else {
            $arr_option = [
                'where' => ['parentid' => $n_pid],
                'with' => ['child'],
                'field' => ['id', 'name', 'fullname', 'initial', 'parentid', 'logo', 'depth', 'salestate', 'price', 'yeartype', 'productionstate', 'sizetype'],
            ];
            $res = VehicleModelRepository::base_get_all($arr_option)->toarray();
            $res = collect($res)->sortBy('name')->map(function ($value, $key) {
                $value = [
                    'id' => $value['id'],
                    'title' => $value['name'],
                    'children' => $value['child'],
                ];
                return $value;
            })->values()->toArray();

        }

        return hello_success('成功', $res);
    }

    /**
     * 创建保养与汽车的关系
     * @param $data
     * @return array
     */
    public function add_maintain_vehicle($data)
    {
        try {
            if (!empty($data['pid']) && !empty($data['maintain_shop_id'])) {

                MaintainVehicleModelRepository::delete_by_where(['maintain_shop_id' => (int)$data['maintain_shop_id']]);

                $vehicle = [];
                $time = date('Y-m-d H:i:s');
                foreach ($data['pid'] as $item) {
                    $vehicle[] = [
                        'maintain_shop_id' => $data['maintain_shop_id'],
                        'vehicle_model_id' => $item,
                        'created_at' => $time,
                        'updated_at' => $time
                    ];
                }

                $result = MaintainVehicleModelRepository::add_many($vehicle);
                return hello_success('创建成功', $result);
            }

            return hello_error('请勾选车型');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }
}